<template>
  <div>
    <div id="components-form-demo-advanced-search">
      <a-row :gutter="24" style="margin-bottom: 15px">
        <a-col :span="6">
          客户编号：
          <a-select
            show-search
            option-filter-prop="children"
            style="width: 60%"
            :filter-option="filterOption"
            v-model="searchData.tenantId"
          >
            <a-select-option
              :value="item.tenantId"
              v-for="item in accArray"
              :key="item.id"
              :titles="item.title"
            >
              {{ item.companyName + "/" + item.tenantId }}
            </a-select-option>
          </a-select>
        </a-col>
        <a-col :span="6">
          操作类型：
          <a-select
            show-search
            option-filter-prop="children"
            style="width: 60%"
            :filter-option="filterOption"
            v-model="searchData.type"
          >
            <a-select-option value="1" names="库存销毁" key="1">
              库存销毁
            </a-select-option>
            <a-select-option value="2" names="退件销毁" key="2">
              退件销毁
            </a-select-option>
          </a-select>
        </a-col>
        <a-col :span="6">
          <a-button
            type="primary"
            class="searchBtn"
            @click="
              () => {
                getTableList();
              }
            "
          >
            查询
          </a-button>
          <a-button
            style="margin: 0 10px"
            type="primary"
            class="searchBtn"
            @click="resetSearch"
          >
            重置
          </a-button>
        </a-col>
        <a-col :span="6"> </a-col>
      </a-row>
    </div>
    <div class="btn" style="display: flex; margin-top: 10px">
      <div class="news">
        <a-button
          type="primary"
          class="blueBtn"
          style="
            background: #66b1ff;
            color: #fff;
            border: none;
            margin-bottom: 10px;
          "
          @click="showModal"
        >
          创建销毁
        </a-button>
      </div>
    </div>
    <a-spin tip="Loading..." :spinning="spinning">
      <a-table :columns="columns" :data-source="tableList" :pagination="false">
        <!-- sku -->
        <span slot="key" slot-scope="text, record">
          <div v-for="(item, i) in record.infoMapperList" :key="i">
            {{ item.sku }}
          </div>
        </span>
        <!-- 商品名称 -->
        <span slot="revision" slot-scope="text, record">
          <div v-for="(item, i) in record.infoMapperList" :key="i">
            {{ item.skuName }}
          </div>
        </span>
        <!-- 标签 -->
        <span slot="productTag" slot-scope="text, record">
          <div v-for="(item, i) in record.infoMapperList" :key="i">
            {{ item.productTag }}
          </div>
        </span>
        <!-- 仓位 -->
        <span slot="skuName" slot-scope="text, record">
          <div v-for="(item, i) in record.infoMapperList" :key="i">
            {{ item.locationName }}
          </div>
        </span>
        <!-- 销毁数量-->
        <span slot="updateBy" slot-scope="text, record">
          <div v-for="(item, i) in record.infoMapperList" :key="i">
            {{ item.ptNumber }}
          </div>
        </span>
        <!-- 销毁时间-->
        <span slot="createTime" slot-scope="text, record">
          {{
            record.createTime === null || record.createTime === ""
              ? "暂无"
              : record.createTime.replace("T", " ")
          }}
        </span>
      </a-table>
    </a-spin>

    <!-- 分页器 -->
    <div style="margin: 20px 0; text-align: center">
      <a-config-provider>
        <a-pagination
        :current="searchData.current"
          show-size-changer
          :pageSizeOptions="['10', '20', '30']"
          :show-total="
            (total) => `${$t('m.page.Total')} ${total} ${$t('m.page.items')}`
          "
          @showSizeChange="showChange"
          :buildOptionText="
            (props) => ` ${props.value} ${$t('m.page.a')}/${$t('m.page.page')}`
          "
          show-quick-jumper
          :default-current="searchData.current"
          :total="total"
          @change="onChangePage"
        />
      </a-config-provider>
    </div>

    <!-- 新增销毁模态 -->
    <a-modal v-model="visible" title="创建销毁" width="40%">
      <template slot="footer" class="modelBtn">
        <a-button
          @click="visible = false"
          style="background: #d7d7d7; color: #fff; border: none"
          >取消</a-button
        >
        <a-button :loading="loading" type="primary" @click="onSubmit"
          >确定</a-button
        >
      </template>
      <a-form-model
        ref="ruleForm"
        :model="dto"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-model-item label="操作类型" prop="type">
          <a-select
            allowClear
            show-search
            option-filter-prop="children"
            style="width: 100%"
            :filter-option="filterOption"
            v-model="dto.type"
            @change="changeType"
          >
            <a-select-option value="1" names="库存销毁" key="1">
              库存销毁
            </a-select-option>
            <a-select-option value="2" names="退件销毁" key="2">
              退件销毁
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="客户编号" prop="tenantId">
          <a-select
            show-search
            option-filter-prop="children"
            style="width: 100%"
            @change="changeTenantId"
            :filter-option="filterOption"
            v-model="dto.tenantId"
          >
            <a-select-option
              :value="item.tenantId"
              v-for="item in accArray"
              :key="item.id"
              :titles="item.title"
            >
              {{ item.companyName + "/" + item.tenantId }}
            </a-select-option>
          </a-select>
        </a-form-model-item>

        <a-form-model-item label="选择仓库" prop="warehousingId">
          <a-select
            allowClear
            show-search
            option-filter-prop="children"
            style="width: 100%"
            :filter-option="filterOption"
            v-model="dto.warehousingId"
            @change="handleChangeWarehouse"
          >
            <a-select-option
              :value="item.sysStoreHouseId"
              v-for="item in warehouse"
              :key="item.sysStoreHouseId"
            >
              {{ item.storeHouseCode }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="选择销毁SKU" prop="SKUKey">
          <a-select
            placeholder="请选择SKU"
            show-search
            option-filter-prop="children"
            style="width: 100%"
            :filter-option="filterOption"
            @change="changeAddSku"
            v-model="dto.SKUKey"
          >
            <a-select-option
              @click="changeAddSku(item.id, skuOption)"
              :value="item.id"
              v-for="item in SKUchineseName"
              :key="item.id"
              :sku="item.sku"
              :skuname="item.skuName"
              :productTag="item.productTag"
              :remainingNumber="item.remainingNumber"
              :skuId="item.skuId"
              :warehousingId="item.warehousingId"
            >
              {{
                item.sku +
                "|" +
                item.skuName +
                "*" +
                "(库存" +
                item.remainingNumber +
                ")"
              }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form-model>
      <a-table
        :columns="skuColumns"
        :data-source="skuDataSource"
        size="small"
        bordered
        :rowSelection="{
          onSelect: onSelect,
          onSelectAll: onSelectAll,
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange,
        }"
      >
        <span slot="ptNumber" slot-scope="text, record">
          <a-input-number
            size="small"
            v-model="record.ptNumber"
            :min="0"
            :max="record.remainingNumber * 1"
          />
        </span>
      </a-table>
    </a-modal>
  </div>
</template>

<script>
import {
  Destroy_the_SKU,
  DestroySKU_page,
} from "@/apis/system/WM/InventoryOperation";
import {
  getStockTerminal,
  Outbounddel_pageBpi,
} from "@/apis/clientSide/OrderManage/Outbound";
import { mapState } from "vuex";
import { getWhList } from "@/apis/common";
export default {
  created() {
    this.getTableList();
  },
  data() {
    return {
      skuOption: {},
      //销毁SKUKey

      SKUchineseName: [],
      //提交数据
      dto: {
        infoMapperList: [],
        tenantId: null,
        type: null,
        typeName: null,
        warehousingId: null,
        SKUKey: null,
      },
      rules: {
        type: [
          { required: true, message: "请选择操作类型！", trigger: "blur" },
        ],
        tenantId: [
          { required: true, message: "请选择客户ID！", trigger: "blur" },
        ],
        warehousingId: [
          { required: true, message: "请选择仓库！", trigger: "blur" },
        ],
        SKUKey: [
          { required: true, message: "请选择销毁SKU！", trigger: "blur" },
        ],
      },
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
      loading: false,
      visible: false,
      searchData: {
        current: 1,
        size: 10,
        tenantId: null,
        type: null,
      },
      tableList: [],
      spinning: false,
      total: 1,
      // 选中行
      selectedRowKeys: [],
      // SKU表格数据
      skuDataSource: [],
      // SKU选择框
      selectionRowsPlus: [],
      //仓库数组
      warehouse: [],
      // SKU分页
      skuPage: {
        size: 1,
        current: 1,
      },
    };
  },
  methods: {
    //销毁类型改变
    changeType(value, option) {
      this.dto.typeName = option.data.attrs.names;
      this.dto.type = value;
    },
    //改变客户编号
    async changeTenantId(value) {
      let { code, responseBody } = await getWhList(value);
      if (code === "200") {
        this.warehouse = responseBody.filter((item) => {
          return item.warehouseId;
        });
        this.SKUchineseName = [];
        this.skuDataSource = [];
        this.dto.warehousingId = null;
        this.dto.SKUKey = null;
      }
    },
    //改变仓库
    async handleChangeWarehouse(value) {
      let { code, responseBody } = await getStockTerminal(
        value,
        this.dto.tenantId
      );
      if (code === "200") {
        this.SKUchineseName = responseBody;
      }
      this.dto.SKUKey = null;
      this.skuDataSource = [];
    },
    // 添加SKU下拉框
    async changeAddSku(value, option) {
      this.skuVisible = true;
      this.skuOption = { ...option };
      let { code, responseBody } = await Outbounddel_pageBpi({
        stockId: value,
        size: this.skuPage.size,
        current: this.skuPage.current,
      });
      if (code === "200") {
        responseBody.records.forEach((item) => {
          item.createTime = item.createTime.replace("T", "   ");
        });
        this.skuDataSource = responseBody.records;
        this.skuDataSource.forEach((item) => {
          item.ptNumber = 1;
        });
      }
    },
    //   创建销毁
    onSubmit() {
      this.loading = true;
      this.passFlag = true;
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (this.selectionRowsPlus.length >= 1) {
            this.selectionRowsPlus.forEach((item) => {
              item.createTime = null;
              item.updateTime = null;
              item.proId = item.key;
              item.key = null;
              if ((item.ptNumber ?? 0) <= 0) {
                this.passFlag = false;
              }
            });
            // console.log(thselectedRowKeys)
            // console.log(this.selectionRowsPlus)
            if (this.passFlag) {
              this.dto.infoMapperList = this.selectionRowsPlus;
              setTimeout(async () => {
                let { code } = await Destroy_the_SKU(this.dto);
                if (code === "10000") {
                  this.loading = false;
                  this.visible = false;
                  this.getTableList();
                  this.selectionRowsPlus = [];
                  this.selectedRowKeys = [];
                }
              }, 500);
            } else {
              this.loading = false;
              this.$message.error("请输入勾选销毁SKU的销毁数量！");
            }
          } else {
            this.loading = false;
            this.$message.error("请勾选需要销毁的SKU！");
            return false;
          }
        } else {
          this.loading = false;
          return false;
        }
      });
    },
    //显示模态框
    showModal() {
      this.visible = true;
      this.dto = {
        infoMapperList: [],
        tenantId: null,
        type: null,
        typeName: null,
        warehousingId: null,
        SKUKey: null,
      };
      this.skuDataSource = [];
      this.selectedRowKeys = [];
      this.selectionRowsPlus = [];
    },
    //重置
    resetSearch() {
      let current = this.searchData.current;
      let size = this.searchData.size;
      this.searchData = {
        current: current,
        size: size,
        tenantId: null,
        type: null,
      };
      this.getTableList();
    },
    //分页器事件
    onChangePage(pageNumber) {
      this.searchData.current = pageNumber;
      this.getTableList();
    },
    //页码变更
    showChange(size, current) {
      this.searchData.current = size;
      this.searchData.size = current;
      this.getTableList();
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    // 选中
    onSelectChange(selectedRowKeys) {
      this.$nextTick(() => {
        this.selectedRowKeys = selectedRowKeys;
      });
    },
    // SKU模态框选择复选框
    onSelect(record, selected) {
      selected
        ? this.selectionRowsPlus.push(record)
        : this.selectionRowsPlus.splice(
            this.selectionRowsPlus.findIndex((x) => x.id === record.id),
            1
          );
    },
    onSelectAll(selected, selectedRows, changeRows) {
      this.selectionRowsPlus = selected
        ? this.selectionRowsPlus.concat(changeRows)
        : this.selectionRowsPlus.filter(
            (x) => !changeRows.find((i) => i.id === x.id)
          );
    },
    async getTableList() {
      this.spinning = true;
      let { code, responseBody } = await DestroySKU_page(this.searchData);
      if (code === "200") {
        this.tableList = responseBody.records;
        this.total = responseBody.total * 1;
        this.spinning = false;
      }
    },
  },
  computed: {
    ...mapState(["accArray"]),
    columns() {
      return [
        {
          title: "客户编号",
          dataIndex: "tenantId",
          align: "center",
          scopedSlots: { customRender: "tenantId" },

          //  fixed: "left",
        },
        {
          title: "SKU",
          dataIndex: "key",
          scopedSlots: { customRender: "key" },
          align: "center",
        },
        {
          title: "商品名称",
          dataIndex: "revision",
          align: "center",
          scopedSlots: { customRender: "revision" },
        },
        {
          title: "标签编号",
          dataIndex: "productTag",
          align: "center",
          scopedSlots: { customRender: "productTag" },
        },
        {
          title: "仓位",
          dataIndex: "skuName",
          // ellipsis: true,
          scopedSlots: { customRender: "skuName" },
          align: "center",
        },
        {
          title: "销毁数量",
          dataIndex: "updateBy",
          scopedSlots: { customRender: "updateBy" },
          align: "center",
          // ellipsis: true,
        },
        {
          title: "操作类型",
          dataIndex: "typeName",
          scopedSlots: { customRender: "typeName" },
          align: "center",
          // ellipsis: true,
        },
        {
          title: "销毁时间",
          dataIndex: "createTime",
          scopedSlots: { customRender: "createTime" },
          align: "center",
          // ellipsis: true,
        },
        {
          title: "操作人 ",
          dataIndex: "createBy",
          scopedSlots: { customRender: "createBy" },
          align: "center",
        },
      ];
    },
    skuColumns() {
      return [
        {
          title: "箱子编号",
          dataIndex: "boxNumber",
          key: "boxNumber",
        },
        {
          title: "入库时间",
          dataIndex: "createTime",
          key: "createTime",
          scopedSlots: { customRender: "createTime" },
        },
        {
          title: "剩余库存",
          dataIndex: "remainingNumber",
          key: "remainingNumber",
        },
        {
          title: "销毁数量",
          key: "ptNumber",
          dataIndex: "ptNumber",
          scopedSlots: { customRender: "ptNumber" },
        },
      ];
    },
  },
};
</script>

<style lang="less" scoped>
.searchBtn {
  background: #fff;
  color: #3eae7c;
  text-shadow: none;
}
.searchBtn:hover {
  background: #3eae7c;
  color: #fff;
}
</style>